package com.wondream.myframework.app.basictest.compiler;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

/**
 * 动态编译java类，不产生文件
 * @author wangjun
 * @note DynamicCompilation
 * @date 2023-10-12  17:28
 */
public class DynamicCompilation {

    public static void main(String[] args) throws Exception{
        // 1.获取JavaCompiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        // 2.获取StandardJavaFileManager
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        // 3.创建Java源文件
        String path = "";
        String className = "HelloWorld";
        File sourceFile = new File(String.format("%s%s.java", path, className));
        FileWriter writer = new FileWriter(sourceFile);
        writer.write("public class HelloWorld { public static void main(String[] args) { System.out.println(\"Hello World!\"); } }");
        writer.close();

        // 4.编译Java源文件
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
        boolean success = task.call();

        // 5.加载编译后的类
        if (success) {
            URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(".").toURI().toURL()});
            Class<?> clazz = classLoader.loadClass(className);
            Method method = clazz.getMethod("main", String[].class);
            method.invoke(null, new Object[]{null});
        }
    }
}

